package org.example.edusmart.controller.UserInfo;

import jakarta.servlet.http.HttpServletRequest;
import org.example.edusmart.pojo.UserPojo;
import org.example.edusmart.request.UserInfo.ChangeUserInfoPojo;
import org.example.edusmart.service.UserService;
import org.example.edusmart.utils.GetTokenInfo;
import org.example.edusmart.utils.Result;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;

@RequestMapping("/userInfo")
@RestController
public class ChangeUserInfoController {
    @Autowired
    private UserService userService;

    @Autowired
    private GetTokenInfo getTokenInfo;

    /**
     * 修改个人信息(修改头像，地址，性别)
     * @param user 前端入参
     * @param request 请求头，token所在位置
     * @return 状态码
     */
    @PostMapping("/changeUserInfo/")
    @PreAuthorize("hasAuthority('public_permission')") //指明有公共权限的才能访问
    public Result changeUserInfo(HttpServletRequest request, @NotNull @RequestBody ChangeUserInfoPojo user){
        //获取用户ID
        String userId = getTokenInfo.getUserIdByJwt(request);
        //根据id获得该用户
        UserPojo User = userService.getUserByUserId(userId);
        //修改个人信息
        HashMap<String, Object> info = new HashMap<>() {{
            put("username", User.getUsername());
            put("email", User.getEmail());
            put("avatar", user.getAvatar());
            put("province", user.getProvince());
            put("city", user.getCity());
            put("district", user.getDistrict());
            put("gender", user.getGender());
        }};
        userService.changeUserInfo(info);
        return new Result(200,"修改成功");
    }
}
